/*
 * @Descripttion: 调整权限路由
 * @Author: caijj
 * @Date: 2020-12-25 17:04:42
 * @LastEditors: caijj
 * @LastEditTime: 2020-12-28 09:47:32
 */
import { constantRoutes } from '@/router/index';
import { getMyMenuTree } from '@/api/user';
import componentMap from '@/router/component.js';
// import Layout from '@/layout/index';

const permission = {
  namespaced: true,
  state: {
    routers: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = constantRoutes.concat(routers);
    }
  },
  actions: {
    getAsyncRouter({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求接口获取路由权限数据
        getMyMenuTree()
          .then(({ data = undefined } = {}) => {
            if (!data) return resolve([]);
            const asyncRouter = filterAsyncRouter(data);
            asyncRouter.push({ path: '*', redirect: '/404', hidden: true });
            commit('SET_ROUTERS', asyncRouter);
            resolve(asyncRouter);
          })
          .catch(err => {
            console.log('getMyMenuTree-err:', err);
            reject(err);
          });
      });
    }
  }
};

export const filterAsyncRouter = (routers) => {
  // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    if (router.component) {
      const component = router.component;
      router.component = loadComponent(component);
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children);
    }
    return true;
  });
};

export const loadComponent = (name) => {
  // return (resolve) => require([`@/views/${view}`], resolve);
  return componentMap[name];
};

export default permission;
